<template>
  <base-view class="custom" :model="query" @submit="search">
    <template v-slot:params>
      <a-col span="8">
        <a-form-item label="商户号">
          <a-input placeholder="请输入商户号" v-model="query.mchntNo" />
        </a-form-item>
      </a-col>
      <a-col span="8">
        <a-form-item label="商户名称">
          <a-input placeholder="请输入商户名称" v-model="query.mchntName" />
        </a-form-item>
      </a-col>
      <a-col span="8">
        <a-form-item label="收单机构">
          <pagination-search-select v-model="query.signInstId" :listUrl="listUrl[0]" :listUrlParam="listUrlParam"
                                    valueName="id" :showNameArr="showNameArr"
                                    :pageSize="10" :openSearch="true" :searchWordKeyArr="signInstIdSearchKey">
          </pagination-search-select>
        </a-form-item>
      </a-col>
      <a-col span="8">
        <a-form-item label="代理机构">
          <pagination-search-select v-model="query.agentMchntNo" :listUrl="listUrl[1]" :listUrlParam="listUrlParam"
                                    valueName="id" :showNameArr="showNameArr"
                                    :pageSize="10" :openSearch="true" :searchWordKeyArr="agentMchntSearchKey">
          </pagination-search-select>
        </a-form-item>
      </a-col>
      <a-col span="8">
        <a-form-item label="商户状态">
          <a-select placeholder="请选择商户状态" v-model="query.mchntStatus">
            <a-select-option value="00">非正式</a-select-option>
            <a-select-option value="01">正式</a-select-option>
            <a-select-option value="02">停用</a-select-option>
            <a-select-option value="03">已注销</a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col span="8">
        <a-form-item label="商户等级">
          <a-select  placeholder="请选择商户等级" v-model="query.mchntLevel"  @click.native="getMchntLevelList()">
            <a-select-option value="">请选择...</a-select-option>
            <a-select-option v-for="item in mchntLevelList"  :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col span="8">
        <a-form-item label="商户商圈">
          <a-select  placeholder="请选择商户商圈" v-model="query.mchntArea"  @click.native="getMchntAreaList()">
            <a-select-option v-for="item in mchntAreaList"  :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col span="8">
        <a-form-item label="平台商户">
          <a-select  placeholder="请选择平台商户" v-model="query.platMchntNo"  @click.native="getPlatMchntList()">
            <a-select-option v-for="item in platMchntList"  :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="24">
      <a-form-model-item class="search">
        <a-button type="primary" html-type="submit">搜索</a-button>
        <a-button style="margin-left: 8px" html-type="reset" @click="reset">重置</a-button>
      </a-form-model-item>
      </a-col>
    </template>
    <div class="btn-group">
      <a-button type="primary" @click="add"><a-icon type="plus"/><span>增加</span></a-button>
      <a-button type="primary" @click="cashWithdrawal"><span>开通提现</span></a-button>
      <a-button type="primary" @click="upload"><span>导入</span></a-button>
      <a-button type="primary" @click="gridExport"><span>导出</span></a-button>
      <a-button type="primary" @click="accSign"><span>核心账户签约</span></a-button>
    </div>
    <div class="section">
      <a-table ref="table" :rowSelection="{selectedRowKeys: selectedRowKeys,hideDefaultSelections:true,type:'radio', onChange: onSelectChange}" :rowKey="(record, index) => {return index;}" :columns="columns" :dataSource="dataSource" :loading="loading" :pagination="pagination" :scroll="{ x: 1500 }" @change="pageChange" @showSizeChange="pageChange">
        <template slot="historyOperate" slot-scope="text, record">
          <a-icon
            type="eye"
            theme="twoTone"
            twoToneColor="#4a9ff5"
            @click="historyView(record)"
            title="查看"
          ></a-icon>
        </template>
        <template slot="WXOperate" slot-scope="text, record">
          <p v-if="record.wechatExpandStatus === '00'"><a @click="thirdEntry(record,'01','2')">微信进件查询</a></p>
          <p v-if="record.wechatExpandStatus === '02'"><a @click="thirdEntry(record,'01','0')">微信进件</a></p>
          <p v-if="typeof record.wechatMchntNo !== 'undefined' && record.wechatExpandStatus !== '02'">{{record.wechatMchntNo}}</p>
        </template>
        <template slot="ALOperate" slot-scope="text, record">
          <p v-if="record.alipayExpandStatus === '00'"><a @click="thirdEntry(record,'02','2')">支付宝进件查询</a></p>
          <p v-if="record.alipayExpandStatus === '02'"><a @click="thirdEntry(record,'02','0')">支付宝进件</a></p>
          <p v-if="typeof record.alipayMchntNo !== 'undefined' && record.alipayExpandStatus !== '02'">{{record.alipayMchntNo}}</p>
        </template>
        <template slot="realNameOperate" slot-scope="text, record">
          <p v-if="record.realNameFlag === 'N'"><a @click="wechatRealNameApply(record)">微信实名认证</a></p>
          <p v-if="record.realNameFlag === 'Y'"><a>实名认证成功</a></p>
          <p v-if="record.realNameFlag === 'I'"><a @click="wechatRealNameAuditQuery(record)">实名认证查询</a></p>
          <p v-if="record.realNameFlag === 'M'"><a @click="wechatRealNameAuditQuery(record)">待商户确认</a></p>
          <p v-if="record.realNameFlag === 'R'"><a @click="wechatRealNameAuditQuery(record)">重新申请</a></p>
          <span v-if="record.realNameFlag === 'I' || record.realNameFlag === 'M' || record.realNameFlag === 'R'"><a style='color: #ff0016 !important' @click="wechatRealNameApplyCancel(record)">实名认证撤销</a></span>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-icon
            type="setting"
            theme="twoTone"
            twoToneColor="#4a9ff5"
            @click="edit(record)"
            v-if="record.mchntStatus !== '02' && record.mchntStatus !== '03' "
            title="修改"
          ></a-icon>
          <a-icon
            type="check-circle"
            theme="twoTone"
            twoToneColor="#4a9ff5"
            @click="changeStatus(record,'use')"
            v-if="record.mchntStatus === '02'"
            title="启用"
          ></a-icon>
          <a-icon
            type="minus-circle"
            theme="twoTone"
            twoToneColor="#4a9ff5"
            @click="changeStatus(record,'stop')"
            v-if="record.mchntStatus === '01'"
            title="停用"
          ></a-icon>
          <a-icon
            type="eye"
            theme="twoTone"
            twoToneColor="#4a9ff5"
            @click="view(record)"
            title="查看"
          ></a-icon>
          <a-icon
            type="delete"
            theme="twoTone"
            twoToneColor="#4a9ff5"
            title="注销"
            @click="changeStatus(record,'cancel')"
            v-if="record.mchntStatus !== '03' && record.mchntStatus !== '00'"
          ></a-icon>
        </template>
      </a-table>
    </div>
    <merchant-base-info-operation ref="modalForm"></merchant-base-info-operation>
    <a-modal :maskClosable="false" v-model="historyModalVisible" title="历史操作记录详情" width="1200px">
      <history-operate ref="modalTable"></history-operate>
    </a-modal>
    <a-modal :maskClosable="false" v-model="uploadModalVisible" title="导入" @ok="handleUpload" okText="导入">
      <a-card :bordered="false">
        <a-col span="12">
          <a-upload class="upload-area" :file-list="fileList" :disabled="fileList.length === 1" :customRequest="selfUpload" :before-upload="beforeUpload">
            <a-button>
              <a-icon type="upload"/>
              选择.xls文件
            </a-button>
            <a-tooltip placement="bottom"  v-if="fileList.length === 1">
              <template slot="title">
                <span>清除</span>
              </template>
              <a-icon :type="'delete'" theme="twoTone" twoToneColor="#4a9ff5" @click="handleRemove" />
            </a-tooltip>
          </a-upload>
        </a-col>
        <a-col span="12">
          <a-button type="primary" @click="downloadTemplate"><span>下载导入模板</span></a-button>
        </a-col>
      </a-card>
    </a-modal>
  </base-view>
</template>

<script>
import MerchantBaseInfoOperation from './MerchantBaseInfoOperation'
import HistoryOperate from './HistoryOperate'
import PaginationSearchSelect from '@/components/select/PaginationSearchSelect'
export default {
  name: 'MerchantBaseInfo',
  components: {MerchantBaseInfoOperation,HistoryOperate,PaginationSearchSelect},
  provide: function () {
    return {
      merchantBaseInfoContext: this
    }
  },
  data: function () {
    return {
      modalVisible: false,
      historyModalVisible: false,
      uploadModalVisible: false,
      operationType: 'view',
      showNameArr:['id','name'],
      listUrl: ['/admin/merParam/UpmpOrganization/organizationSelectList', '/admin/mcmp/bMchntBaseInfo/agentMchntSelect2List'],
      listUrlParam: {'instId': ''},
      signInstIdSearchKey:['orgCode'],
      agentMchntSearchKey:['agentMchntNo'],
      query: {
        instId: '',
        mchntNo: '',
        mchntName: '',
        signInstId: '',
        agentMchntNo: '',
        mchntStatus: undefined,
        mchntLevel: '',
        mchntArea: '',
        platMchntNo: '',
        prodStatus: '',
        auditStatus: '',
      },
      loading: false,
      pagination: {
        pageNum: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) =>
          `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      columns: [
        {
          title: '收单机构',
          dataIndex: 'signInstName',
          width: 120,
        },
        {
          title: '商户号',
          dataIndex: 'mchntNo',
          width: 160,
        },
        {
          title: '商户名称',
          dataIndex: 'mchntName',
          width: 150,
        },
        {
          title: '所属代理机构',
          dataIndex: 'agentMchntNo',
          width: 150,
        },
        {
          title: '商户商圈',
          dataIndex: 'mchntArea',
          width: 120,
        },
        {
          title: '审核状态',
          dataIndex: 'auditStatus',
          width: 150,
          customRender (text) {
            return text ? {
              "00": "新增待提交审批",
              "01": "新增待审核",
              "02": "新增审核通过",
              "03": "新增审核拒绝",

              "10": "注销待提交审批",
              "11": "注销待审核",
              "12": "注销审核通过",
              "13": "注销审核拒绝",

              "20": "停用待提交审批",
              "21": "停用待审核",
              "22": "停用审核通过",
              "23": "停用审核拒绝",

              "30": "启用待提交审批",
              "31": "启用待审核",
              "32": "启用审核通过",
              "33": "启用审核拒绝",

              "40": "修改待提交审批",
              "41": "修改待审核",
              "42": "修改审核通过",
              "43": "修改审核拒绝",
            }[text] : ""
          }
        },
        {
          title: '商户状态',
          /**
           * 00 非正式
           * 01 正式
           * 02 停用
           * 03 已注销
           */
          dataIndex: 'mchntStatus',
          customRender (text) {
            return text ? ["非正式", "正式", "停用", "已注销"][+text] : ""
          },
          width: 120,
        },
        {
          title: '微信商户号',
          dataIndex: 'wechatExpandStatus',
          scopedSlots: { customRender: "WXOperate" },
          width: 200,
        },
        {
          title: '支付宝商户号',
          dataIndex: 'alipayExpandStatus',
          scopedSlots: { customRender: "ALOperate" },
          width: 200,
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 120,
        },
        {
          title: '审核通过时间',
          dataIndex: 'lastAuditTime',
          width: 120,
        },
        {
          title: '法人行',
          dataIndex: 'instId',
          width: 120,
        },
        {
          title: '历史操作记录',
          dataIndex: 'operate1',
          scopedSlots: { customRender: "historyOperate" },
          width: 150,
        },
        {
          title: '微信实名认证状态',
          dataIndex: 'realNameFlag',
          scopedSlots: { customRender: "realNameOperate" },
          width: 150,
        },
        {
          title: "操作",
          scopedSlots: { customRender: "operation" },
          fixed: "right",
          width: 120,
        },
      ],
      dataSource: [],
      signInstIdList: [],
      agentMchntList: [],
      mchntLevelList: [],
      mchntAreaList: [],
      platMchntList: [],
      initFlag:true,
      selectedRowKeys:[],
      fileList:[],
    }
  },
  methods: {
    init(){
      if(this.initFlag){
        this.getMchntLevelList()
        this.getPlatMchntList()
        this.getMchntAreaList()
        this.initFlag = false
      }
    },
    async getMchntLevelList() {
      try {
        const res = await this.$get("/admin/mcmp/bMchntBaseInfo/mchntLevelSelect2List", {
          q:encodeURIComponent(`&${this.query.instId}`)
        });
        if (res.status === 200) {
          this.mchntLevelList = res.data.results;
        }
      } catch (e) {
        console.error(e);
      }
    },
    async getPlatMchntList() {
      try {
        const res = await this.$get("/admin/mcmp/bMchntBaseInfo/platMchntSelect2List", {
          q:encodeURIComponent(`&${this.query.instId}`)
        });
        if (res.status === 200) {
          this.platMchntList = res.data.results;
        }
      } catch (e) {
        console.error(e);
      }
    },
    async getMchntAreaList() {
      try {
        const res = await this.$get("/admin/mcmp/bMchntBaseInfo/mchntAreaSelect2List", {
          q:encodeURIComponent(`&${this.query.instId}`)
        });
        if (res.status === 200) {
          this.mchntAreaList = res.data.results;
        }
      } catch (e) {
        console.error(e);
      }
    },

    async reset(){
      this.query = {instId:this.query.instId}
      this.pagination.pageNum = this.pagination.defaultCurrent;
      this.pagination.pageSize = this.pagination.defaultPageSize;
      await this.search();
    },
    async search(e) {
      e && e.preventDefault && e.preventDefault();
      try {
        const res = await this.$get("/admin/mcmp/bMchntBaseInfo/list", {
          instId: this.query.instId,
          mchntNo: this.query.mchntNo,
          mchntName: this.query.mchntName,
          signInstId: this.query.signInstId,
          agentMchntNo: this.query.agentMchntNo,
          mchntStatus: this.query.mchntStatus,
          mchntLevel: this.query.mchntLevel,
          mchntArea: this.query.mchntArea,
          platMchntNo: this.query.platMchntNo,
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize,
        });
        this.dataSource = res.data.rows;
        this.$set(this.pagination, "total", +res.data.total);
        this.init()
      } catch (e) {
        console.error(e);
      }
    },
    openModal (type = 'add', beanInfo) {
      if (type !== 'add' && type !== 'view' && (beanInfo.auditStatus === '01' || beanInfo.auditStatus === '21' || beanInfo.auditStatus === '31' || beanInfo.auditStatus === '41')) {
        const h = this.$createElement;
        this.$warning({
          title: '提示',
          content: h('div', {}, [
            h('p', '审批流程中的数据不允许修改'),
          ]),
          onOk() {},
        });
        return
      }
      this.$refs.modalForm.openModal(type, beanInfo,this.query.instId)
    },
    async submit () {
      const res = await this.$refs.modalForm.submit()
      if (res) {
        this.modalVisible = false
        this.pagination.defaultCurrent = 1
        await this.search()
      }
    },
    historyView (item){
      this.historyModalVisible = true;
      this.$nextTick(() => {
        this.$refs.modalTable.setBeanInfo(item,this.query.instId);
      });
    },
    add (){
      const item = {
        mchntNo:""
      }
      this.openModal('add', item)
    },
    edit (item) {
      this.openModal('edit', item)
    },
    view (item) {
      this.openModal('view', item)
    },
    changeStatus(item,type) {
      this.openModal(type, item);
    },
    pageChange(e) {
      this.pagination.pageNum = e.current;
      this.pagination.pageSize = e.pageSize;
      this.search();
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    async accSign(){
      if(this.selectedRowKeys.length < 1){
        this.$message.warning("请先选择一条数据!");
        return false
      }else{
        let obj = this;
        let index = this.selectedRowKeys[0];
        let info = this.dataSource[index];
        if(info.mchntStatus !== '01'){
          this.$message.warning("请选择正式状态的商户!");
          return false
        }
        const param = {
          mchntNo:info.mchntNo,
          acctNo:info.settleAcctNo,
          instId:this.query.instId
        }
        this.$confirm({
          title: '核心账户签约',
          content: '确定去签约核心结算账户吗?',
          okText: '确认',
          cancelText: '取消',
          async onOk(){
            const res = await obj.$post("/admin/mcmp/bMchntBaseInfo/accSign",param)
            if (res.data.code === "100000") {
              obj.$message.success("核心账户签约成功！");
              return true;
            } else {
              obj.$message.error(res.data.data.respMsg);
              return false;
            }
          }
        });
      }
    },
    async cashWithdrawal(){
      if(this.selectedRowKeys.length < 1){
        this.$message.warning("请先选择一条数据!");
        return false
      }else{
        let obj = this;
        let index = this.selectedRowKeys[0];
        let info = this.dataSource[index];
        if(info.mchntStatus !== '01'){
          this.$message.warning("请选择正式状态的商户!");
          return false
        }
        const param = {
          mchntNo:info.mchntNo,
          instId:this.query.instId,
          cashWithdrawalFlag:info.cashWithdrawalFlag
        }
        if(info.cashWithdrawalFlag !== "Y"){
          const res = await obj.$get("/admin/mcmp/bMchntBaseInfo/getreqD0",param)
          if (res.data.code === "100000") {
            obj.confirmOpenCashOut(obj,param)
          } else {
            obj.$message.error("该商户不符合开通提现条件，入网超过90天，且连续30天商户每天都有交易，方可开通提现");
            return false;
          }
        }else{
          obj.confirmOpenCashOut(obj,param)
        }

      }
    },
    confirmOpenCashOut(obj,param) {
      this.$confirm({
        title: '开通提现',
        content: '确定去开通提现吗?',
        okText: '确认',
        cancelText: '取消',
        async onOk(){
          const res = await obj.$post("/admin/mcmp/bMchntBaseInfo/openCashOut",param)
          if (res.data.code === "100000") {
            return true;
          } else {
            obj.$message.error("该商户不符合开通提现条件，入网超过90天，且连续30天商户每天都有交易，方可开通提现");
            return false;
          }
        }
      });
    },
    async wechatRealNameApply(record){
      if(record.mchntStatus !== '01'){
        this.$message.warning("请选择正式状态的商户!");
        return false
      }
      const param = {};
      param.mchntNo = record.mchntNo;
      param.instId = record.instId;
      const res = await this.$post("/admin/mcmp/bMchntBaseInfo/wechatRealNameApply",param)
      if (res.data.code === "100000") {
        return true;
      } else {
        this.$message.error(res.data.data.respMsg);
        return false;
      }
    },
    async wechatRealNameAuditQuery(record){
      if(record.mchntStatus !== '01'){
        this.$message.warning("请选择正式状态的商户!");
        return false
      }
      const param = {};
      param.mchntNo = record.mchntNo;
      param.instId = record.instId;
      param.realNameApplyNo = record.realNameApplyNo;
      const res = await this.$post("/admin/mcmp/bMchntBaseInfo/wechatRealNameAuditQuery",param)
      if (res.data.code === "100000") {
        return true;
      } else {
        this.$message.error(res.data.data.respMsg);
        return false;
      }
    },
    async wechatRealNameApplyCancel(record){
      if(record.mchntStatus !== '01'){
        this.$message.warning("请选择正式状态的商户!");
        return false
      }
      const param = {};
      param.mchntNo = record.mchntNo;
      param.instId = record.instId;
      param.realNameApplyNo = record.realNameApplyNo;
      const res = await this.$post("/admin/mcmp/bMchntBaseInfo/wechatRealNameApplyCancel",param)
      if (res.data.code === "100000") {
        return true;
      } else {
        this.$message.error(res.data.data.respMsg);
        return false;
      }
    },
    async gridExport(){
      const res = await this.$download("/admin/mcmp/bMchntBaseInfo/gridExport", {
        instId: this.query.instId,
        mchntNo: this.query.mchntNo,
        mchntName: this.query.mchntName,
        signInstId: this.query.signInstId,
        agentMchntNo: this.query.agentMchntNo,
        mchntStatus: this.query.mchntStatus,
        mchntLevel: this.query.mchntLevel,
        mchntArea: this.query.mchntArea,
        platMchntNo: this.query.platMchntNo,
        exportFlag: "bMchntBaseInfoExportFlag",

      }, '商户批量导出.xlsx');
    },
    downloadTemplate() {
      this.$download('/admin/mcmp/bMchntBaseInfo/getTemplate', {}, '商户批量导入模板.xls')
    },
    upload() {
      this.uploadModalVisible = true
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    selfUpload({action, file, onSuccess, onError, onProgress}) {
      this.fileList = [...this.fileList, file]
    },
    handleUpload() {
      const {fileList} = this
      const formData = new FormData()
      formData.append('excelFile', fileList[0])
      formData.append('instId', this.query.instId)
      this.$upload('/admin/mcmp/bMchntBaseInfo/upload', formData).then((r) => {
        this.$message.success(r.data.message)
        this.fileList = []
      }).catch((r) => {
        console.error(r)
        this.fileList = []
        this.$message.error(r.data.message)
      })
    },
    async thirdEntry(record,channelFlag,opr){
      var param = {};
      param.mchntNo = record.mchntNo;
      param.opr = opr;//0入驻，1修改，2查询
      param.channelFlag = channelFlag;//01微信，02支付宝
      param.instId = this.query.instId;
      param.mchntBizFlag = "00";
      const res = await this.$post("/admin/mcmp/bMchntBaseInfo/thirdEntry",param)
      const h = this.$createElement;
      if(res.data.code === '100000'){
        this.$success({
          title: '提示',
          content: h('div', {}, [
            h('p', res.data.message),
          ]),
          onOk() {
          },
        });
      }else{
        this.$error({
          title: '提示',
          content: h('div', {}, [
            h('p', res.data.message),
          ]),
          onOk() {
          },
        });
      }
    },
    beforeUpload(file) {
      const isexcel = file.type === "application/vnd.ms-excel"
      if (!isexcel) {
        this.$message.error('请上传xls文件');
      }
      return isexcel;
    },
  },
  mounted() {
  },
  watch: {
    'query.instId'(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.listUrlParam= {'instId': newValue}
      }
    }
  }
}
</script>

<style scoped>
.page {
  width: 100%;
}

.section {
  background: #fff;
}

.form {
  text-align: center;
}
.select {
  width: 180px;
}

.btn-group {
  margin-bottom: 20px;
}
.subtitle{
  width: 100%;
  font-size: 16px;
  margin-bottom: 10px;
  padding: 0 10px;
}
</style>
